package com.whh.permission.controller;

import com.github.pagehelper.PageInfo;
import com.whh.permission.po.AssetScrap;
import com.whh.permission.po.File;
import com.whh.permission.po.User;
import com.whh.permission.service.IFileService;
import com.whh.permission.util.JsonObject;
import com.whh.permission.util.R;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
public class FileController {
    @Resource
    private IFileService fileServiceImpl;


    @RequestMapping("file/queryFileInfo")
    @ResponseBody
    public JsonObject queryFileInfo(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10")Integer limit,File file){

        JsonObject object=new JsonObject();
        PageInfo<File> pageInfo=fileServiceImpl.queryFile(page,limit,file);
        object.setCode(0);
        object.setCount(pageInfo.getTotal());
        object.setData(pageInfo.getList());
        object.setMsg("ok");
        return object;
    }


    /**
     * 删除文件信息
     * @param ids
     * @return
     * @throws FileNotFoundException
     */
    @RequestMapping("file/delete")
    @ResponseBody
    public R delete(String ids) throws FileNotFoundException {
        List list = Arrays.asList(ids.split(","));
        for (Object id:list){
            int i = Integer.parseInt((String) id);
            //根据id查询信息
            File file = fileServiceImpl.queryFileById(i);
            //删除文件
            String realPath = ResourceUtils.getURL("classpath:").getPath().replace("%20"," ") + "/static"+file.getPath();
            java.io.File fileObj = new java.io.File(realPath,file.getNewFileName());
            if (fileObj.exists()) fileObj.delete();//立即删除
        }


        fileServiceImpl.deleteByIds(list);
        return R.ok();
    }

    @RequestMapping("file/download/{id}")
    public void download(@PathVariable("id") Integer id,HttpServletResponse response) throws IOException {
        String openStyle = "attachment";
        System.out.println("trigger download");
        getFile(openStyle,id,response);
    }


    @RequestMapping("file/uploadFile")
    @ResponseBody
    public R uploadFile(@RequestParam("file") MultipartFile aaa, HttpSession session, HttpServletRequest request) throws IOException {
        //获取用户的id
        User user = (User) session.getAttribute("user");
        //获取文件原始名称
        String originalFilename = aaa.getOriginalFilename();
        //获取文件后缀
        String extension = "."+ FilenameUtils.getExtension(aaa.getOriginalFilename());
        //生成新的文件名称
        String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + UUID.randomUUID().toString().replace("-", "") + extension;

        //文件大小
        long size = aaa.getSize();
        //文件类型
        String type = aaa.getContentType();

        //处理根据日期生成目录
        String realPath = ResourceUtils.getURL("classpath:").getPath().replace("%20"," ") + "static/files";
        String dateFormat = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String dateDirPath = realPath+"/"+ dateFormat;
        java.io.File dateDir = new java.io.File(dateDirPath);
        if (!dateDir.exists()) dateDir.mkdirs();


        //处理文件上传
        aaa.transferTo(new java.io.File(dateDir,newFileName));

        //将文件信息放入数据库中
        File file = new File();
        file.setOldFileName(originalFilename).setNewFileName(newFileName).setExt(extension).setSize(String.valueOf(size))
                .setType(type).setPath("/files/"+dateFormat).setUId(user.getId());

        fileServiceImpl.addFileInfo(file);
        return R.ok();
    }

    @RequestMapping("file")
    public String fileIndex(){
        return "pages/file";
    }





    public void getFile(String openStyle, Integer id, HttpServletResponse response) throws IOException {
        File file = fileServiceImpl.queryFileById(id);
        // 获取文件信息
        final String realPath = ResourceUtils.getURL("classpath:").getPath().replace("%20"," ") + "/static"+file.getPath();

        // 获取文件输入流
        FileInputStream is = new FileInputStream(new java.io.File(realPath,file.getNewFileName()));
        // 附件下载
        response.setHeader("content-disposition", openStyle+";filename=" + URLEncoder.encode(file.getOldFileName(), "UTF-8"));
        // 获取响应response输出流
        ServletOutputStream os = response.getOutputStream();
        // 文件拷贝
        IOUtils.copy(is, os);
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
        // 更新下载次数
        if(openStyle.equals("attachment")){
            file.setDowncounts(file.getDowncounts() + 1);
            fileServiceImpl.updateFile(file);
        }
    }
}
